package pub.guoxin.oops.common.sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pub.guoxin.oops.model.SeqGenerator;
import pub.guoxin.oops.repository.SeqGeneratorRepository;

import java.util.Objects;


/**
 * Created by guoxin on 17-11-13.
 */
@Component("communicationGenerator")
public class CommunicationGeneratorImpl implements SeqGeneratorProvider {

    public static final String COMMUNICATION_SEQ = "communication_seq";

    @Autowired
    private SeqGeneratorRepository generatorRepository;

    @Override
    public Long nextSequence() {
        SeqGenerator seq = generatorRepository.findOne(COMMUNICATION_SEQ);
        if (!Objects.isNull(seq)) {
            seq.setSeq(seq.getSeq() + 1);
            SeqGenerator save = generatorRepository.save(seq);
            return save.getSeq();
        }
        SeqGenerator save = generatorRepository.save(new SeqGenerator(COMMUNICATION_SEQ, START_0L));
        return save.getSeq();
    }
}
